﻿using D.IdentityDbStore.DbContext;
using D.IdentityDbStore.Entities;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System.Threading.Tasks;

namespace D.IdentityDbStore.Stores
{
    public class CorsPolicyService : ICorsPolicyService
    {
        private readonly ILogger<CorsPolicyService> _logger;
        private readonly ISqlSugarClient _db;

        public CorsPolicyService(ILogger<CorsPolicyService> logger, DbSql dbSql)
        {
            _logger = logger;
            _db = dbSql.Db;
        }

        public Task<bool> IsOriginAllowedAsync(string origin)
        {
            //select distinct Origin from ClientCorsOrigins where Origin is not null
            var isAllowed = _db.Queryable<ClientCorsOrigin>()
                                     .Where(m => m.Origin.ToLower() == origin.ToLower()).Count() > 0;

            _logger.LogDebug($"Origin {origin} is allowed: {isAllowed}");
            return Task.FromResult(isAllowed);
        }
    }
}
